const { userService } = require('../../services/index');

Page({
  data: {
    username: '',
    password: '',
    isLoading: false
  },

  onLoad() {
    // 检查是否已登录
    if (getApp().globalData.isLoggedIn) {
      wx.redirectTo({
        url: '/pages/index/index'
      });
    }
  },

  onUsernameChange(e) {
    this.setData({ username: e.detail });
  },

  onPasswordChange(e) {
    this.setData({ password: e.detail });
  },

  async handleLogin() {
    const { username, password } = this.data;
    
    // 表单验证
    if (!username || !password) {
      this.showNotify('请输入账号和密码');
      return;
    }
    
    this.setData({ isLoading: true });
    
    try {
      // 调用登录API
      const res = await userService.login({
        username,
        password
      });
      
      // 登录成功，保存用户信息和token
      getApp().login(res.userInfo, res.token);
      
      // 检查是否有情侣关系
      if (getApp().globalData.coupleInfo) {
        wx.switchTab({
          url: '/pages/index/index'
        });
      } else {
        wx.redirectTo({
          url: '/pages/couple/bind'
        });
      }
      
    } catch (error) {
      // 登录失败，显示错误信息
      this.showNotify(error.message || '登录失败');
    } finally {
      this.setData({ isLoading: false });
    }
  },

  navToRegister() {
    wx.redirectTo({
      url: '/pages/register/index'
    });
  },

  showNotify(message) {
    this.selectComponent('#notify').show({
      message,
      duration: 2000,
      color: '#fff',
      background: '#FF6B8B'
    });
  }
});